package com.fenghui.doubantop.utils;

import com.fenghui.doubantop.domain.Book;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

/**
 * 书籍解析工具类，继承自抽象的解析工具类
 */
public class BookParseUtil extends ParseUtil<Book> {

    @Override
    protected void extractInfo(Element child, Book book) {
        // 书籍主页 url  通过 url 获取文件名，也是书籍索引
        String bookIndex = child.select("table tbody tr td a").attr("href").trim();
        String bookId = BaseUtils.extractNumber(bookIndex);
        book.setBookId(Integer.valueOf(bookId));

        // 书籍封面图片 URL
        String bookUrl = child.select("table tbody tr td a img").attr("src").trim();
        book.setBookUrl(bookUrl);

        // 书籍名称
        String bookTitle = child.select("table tbody tr td div a").text().trim();
        book.setBookTitle(bookTitle);

        //获取书籍信息块  杨本芬 / 北京联合出版公司 / 2020-6 / 38.00元
        String s2 = child.select("table tbody tr td p.pl").text().trim();
        // System.out.println(s2);
        String author = "", publisher = "", year = "", price = "";
        if (s2.split("/").length == 4) {
            // 作者
            author = s2.split("/")[0];
            // 出版社
            publisher = s2.split("/")[1];
            // 年代
            year = s2.split("/")[2];
            // 价格
            price = s2.split("/")[3];
        } else if (s2.split("/").length == 3) {
            // 出版社
            publisher = s2.split("/")[0];
            // 年代
            year = s2.split("/")[1];
            // 价格
            price = s2.split("/")[2];
        } else {
            // 作者
            author = s2.split("/")[0] + '/' + s2.split("/")[1];
            // 出版社
            publisher = s2.split("/")[2];
            // 年代
            year = s2.split("/")[3];
            // 价格
            price = s2.split("/")[4];
        }

        book.setAuthor(author);
        book.setPublisher(publisher);
        book.setYear(year);
        price = price.replaceAll("[^0-9.]", "");
        book.setPrice(Double.valueOf(price));

        // 评分
        String rating_nums = child.select("table tbody tr td div  span.rating_nums").text().trim();
        book.setRatingNums(Double.valueOf(rating_nums));

        // 评价人次
        String remarkNum = child.select("table tbody tr td div  span.pl").text().trim();
        remarkNum = BaseUtils.extractNumber(remarkNum);
        book.setRemarkNum(Integer.valueOf(remarkNum));

        // 引述
        String quote = child.select("table tbody tr td   p.quote span.inq").text().trim();
        book.setQuote(quote);
    }

    @Override
    protected Element getElement(Document document) {
        return document.getElementsByClass("indent").get(0);
    }

    @Override
    protected boolean isIgnoredTag(Element element) {
        return "p".equals(element.tagName()) || "div".equals(element.tagName());
    }

    @Override
    protected Book createItem() {
        return new Book();
    }
}
